﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using InsideDL.MISService;
using InsideDL.MISControl;
using InsideDL.MISData;
using System.Diagnostics;
using System.IO;

namespace InsideDL
{
    public partial class frmHRPC : MISControl.frmMatrix
    {
        protected InsideDL.MISService.EXLAPP exlAPP = null;
        protected string shtName = string.Empty;
        protected int row = 0;
        List<HtmlElement> secCollect = null;
        public frmHRPC()
        {
            InitializeComponent();
            ucExecute1.ExecuteClick += new EventHandler(ucClickFacade);
            ucExecute_Exit.ExecuteClick += new EventHandler(ucClickFacade);
            this.controlList = new List<ucSelFileOrPath>
            {
                ucHRPC,ucExcel
            };
        }

        protected override void execute()
        {
            if (base.Vaildation().Equals(false))
            { return; }

            exlAPP = new InsideDL.MISService.EXLAPP();
            exlAPP.OpenFile(ucExcel.Txt);
            setDocument();


            row = 2;

            foreach (HtmlElement el in secCollect)
            {
                if (el.InnerText.Substring(4, 1).Equals("4"))
                {
                    fillToExcelFor4(contentToArray(el.InnerText));            
                }
                else
                {
                    fillToExcel(contentToArray(el.InnerText));            
                }                
            }
            exlAPP.SaveCloseXLS();
            exlAPP = null;
            showMessage(this.Text, "完成！");  
        }

        protected void fillToExcel(string[] p_content)
        {
            string rng = string.Empty;
            foreach (string cnt in p_content)
            {
                rng = "B{0}";
                if (cnt.Substring(0, 1) == " ")
                {
                    rng = "A{0}";
                }
                exlAPP.SetRangeValue(shtName, string.Format(rng,row.ToString())
                    , cnt);
                row++;
            }
        }

        protected void fillToExcelFor4(string[] p_content)
        {
            string rng = string.Empty;
            string[] cols = {"A","B","C"};
            string[] colsValue = { "指標", "單位", "目標" };
            for (int i = 0; i < p_content.Length; i++)
            {
                rng = "A{0}";
                //區段4
                if (i == 0)
                {
                    exlAPP.SetRangeValue(shtName
                        , string.Format(rng, row.ToString())
                   , p_content[i]);
                    row++;
                    //產生出4區段時要的小標題
                    for (int col = 0; col < cols.Length; col++)
                    {
                        exlAPP.SetRangeValue(shtName
                            , cols[col] + row.ToString()
                            , colsValue[col]);
                    }
                }
                if(i > 0)
                {
                    for (int col = 0; col < cols.Length; col++)
                    {
                        if (col.Equals(0))
                        {
                            exlAPP.SetRangeValue(shtName
                               , cols[col] + row.ToString()
                               , p_content[i]);
                        }
                                 
                        if (col > 0)
                        {
                            string[] tmps = p_content[i].Split(
                                new char[] { ':' });
                            exlAPP.SetRangeValue(shtName
                          , cols[col] + row.ToString()
                          , tmps.Length > 1 ? tmps[1]: "" );
                        }
                        i++;               
                    }
                    i--;
                }                               
                row++;
            }         
        }

        protected void setDocument()
        {
            StreamReader file = new StreamReader(ucHRPC.Txt, Encoding.GetEncoding(950));
            string content = file.ReadToEnd();
            file.Close();

            WebBrowser wb = new WebBrowser();
            wb.ScriptErrorsSuppressed = true;
            wb.DocumentText = content;
            do
            {
                Application.DoEvents();
            } while (wb.ReadyState != WebBrowserReadyState.Complete);
            HtmlDocument doc = wb.Document;

            HtmlElement epName = doc.GetElementById("win0divDERIVED_EP_NAME_RESULT");
            shtName = epName.InnerText
                .Substring(0, 4).Trim().Replace("n","").Trim();

            int secLen = 7;
            string secString = "win0divEP_BTN_LINK_WRK_EP_SECTION_HEADER${0}";
            secCollect = new List<HtmlElement>();
            for (int i = 1; i <= secLen; i++)
            {
                HtmlElement sec1 = doc.GetElementById(
                    string.Format(secString, i.ToString()));
                secCollect.Add(sec1);
            }            
        }

        protected string[] contentToArray(string p_content)
        {
            string[] tmp = p_content.Split(Environment.NewLine.ToCharArray()
              , StringSplitOptions.RemoveEmptyEntries);
            List<string> result = new List<string>();
            string t1 = string.Empty;
            string old = string.Empty;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < tmp.Length; i++)
            {
                t1 = string.Empty;
                switch (tmp[i])
                {
                    case "展開 ":
                    case "收合 ":
                    case "描述:":
                    case "區段權重(%): ":
                    case "新增 關鍵指標描述 ":
                        break;
                    //case "權重(%): ":
                    //    result.Add(string.Format("{0}{1}", tmp[i]
                    //        , tmp[i+1]);
                    //    break;
                    case "單位:":
                        old = tmp[i];
                        for (int x = 1; x < 30; x++)
                        {
                            i++;
                            sb.Append(tmp[i]);
                            if((tmp[i].Trim().Length > 0) &
                                (tmp[i + 1 ].Trim().Substring(0,1)
                                .Equals("目")))
                            {
                                break;
                            }
                        }

                        t1 = string.Format("{0}{1}", old,sb.ToString());
                        result.Add(t1);
                        sb.Remove(0, sb.ToString().Length);
                        break;
                    case "目標:":
                        if (tmp[i].Length < 4)
                        {
                            old = tmp[i];
                            if (tmp[i+1].IndexOf('"') > -1)
                            {
                                for (int x = 1; x < 30; x++)
                                {
                                    i++;
                                    sb.Append(tmp[i]);
                                    if (tmp[i].IndexOf('"') > 0)
                                    {
                                        break;
                                    }                              
                                }
                            }
                            else
                            {
                                for (int x = 1; x < 30; x++)
                                {
                                    i++;
                                    sb.Append(tmp[i]);
                                    if (tmp[i].Trim().Length.Equals(0))
                                    {
                                        break;
                                    }
                                }
                            }
                            t1 = string.Format("{0}{1}", old
                                    , sb.ToString());        
                            result.Add(t1);
                            sb.Remove(0, sb.ToString().Length);
                        }
                        break;
                    default:
                        if (!string.IsNullOrEmpty(tmp[i].Trim()))
                        { result.Add(tmp[i]); }
                        break;
                }
            }

            return result.ToArray();
        }
    }
}
